package com.lagou.edu.utils;

import com.lagou.edu.annotition.MyAutowired;
import com.lagou.edu.annotition.MyComponent;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器类，负责手动事务的开启、提交、回滚
 */
@MyComponent("transactionManager")
public class TransactionManager {

//	//禁用构造方法
//	private TransactionManager() {
//	}
//
//	//懒汉式单例模式
//	public static TransactionManager transactionManager = new TransactionManager();
//
//	public static TransactionManager getInstance() {
//		return transactionManager;
//	}

	@MyAutowired
	private ConnectionUtils connectionUtils;

//	public ConnectionUtils getConnectionUtils() {
//		return connectionUtils;
//	}
//
//	public void setConnectionUtils(ConnectionUtils connectionUtils) {
//		this.connectionUtils = connectionUtils;
//	}

	//开启事务
	public void beginTransaction() throws SQLException {
		Connection currentThreadConn = connectionUtils.getCurrentThreadConn();
		currentThreadConn.setAutoCommit(false);

	}

	//提交事务
	public void commit() throws SQLException {
		Connection currentThreadConn = connectionUtils.getCurrentThreadConn();
		currentThreadConn.commit();
	}

	//回滚事务
	public void rollback() throws SQLException {
		Connection currentThreadConn = connectionUtils.getCurrentThreadConn();
		currentThreadConn.rollback();
	}
}
